//
//  UserViewModel.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/1/24.
//

import Foundation
import SwiftUI
import LeanCloud

class UserViewModel: BaseViewModel {
    
    override init() {
        super.init()
        self.addObserve(self, .bindAccount) { (selfInstance, item: (String,String)) in
            selfInstance.doBind(type: item.0, id: item.1)
        }
    }
    
    func upload(image: UIImage) {
        request {
            let time = getMillisecond(try await getNetTime())
            let key = "head_\(userManager.getUserId())_\(time)"
            let bean = try await QiniuManager.shared.upload(image : image, key: key ,modeType: QiniuResult.self)
            try await retry(maxRetries: 5, retryDelayMillis: 300) {
                //删除图片
                _ = try await QiniuManager.shared.delete(url: userManager.getAvatar(), modeType: String.self)
            }
            return bean
        } suc: {
            userManager.user?.headUrl = $0.getUrl()
            userManager.update()
            userManager.request()
            showToast("上传成功")
        } fail: {_ in
            showToast("上传失败")
        }
    }
    
    func doBind(type:String, id: String) {
        if let user = userManager.user {
            request {
                let query = LCQuery(className: "User_")
                query.whereKey(type, .equalTo(id))
                let result = try await retry(maxRetries: 5, retryDelayMillis: 300) {
                    return try await LeancloudManager.instance.getFirst(query: query, modeType: UserBean.self)
                }
                if result == nil {
                    switch(type) {
                    case LoginType.WX.rawValue:
                        user.wx = id
                    case LoginType.QQ.rawValue:
                        user.qq = id
                    case LoginType.APPLE.rawValue:
                        user.apple = id
                    default: break
                        
                    }
                    try await userManager.requestAsync(user: user)
                } else {
                    //数据不为空，已经被绑定了，抛异常
                    switch(type) {
                    case LoginType.WX.rawValue:
                        try check(false,"该微信已经被绑定，请先解绑，才能再次绑定")
                    case LoginType.QQ.rawValue:
                        try check(false,"该QQ已经被绑定，请先解绑，才能再次绑定")
                    case LoginType.APPLE.rawValue:
                        try check(false,"该Apple已经被绑定，请先解绑，才能再次绑定")
                    default: break
                        
                    }
                }
                
                return user
            } suc: {
                userManager.saveUser($0)
            } fail: {
                showToast($0.message)
            }
        }
    }
    
    func unBind(type:String) {
        if let user = userManager.user {
            request {
                switch(type){
                case LoginType.WX.rawValue:
                    try check(!(((user.qq ?? "").isEmpty && (user.apple ?? "").isEmpty)),"解绑失败，微信、QQ、Apple至少绑定一个。")
                    user.wx = ""
                case LoginType.QQ.rawValue:
                    try check(!(((user.wx ?? "").isEmpty && (user.apple ?? "").isEmpty)),"解绑失败，微信、QQ、Apple至少绑定一个。")
                    user.qq = ""
                case LoginType.APPLE.rawValue:
                    try check(!(((user.wx ?? "").isEmpty && (user.qq ?? "").isEmpty)),"解绑失败，微信、QQ、Apple至少绑定一个。")
                    user.apple = ""
                default: break
                    
                }
                try await userManager.requestAsync(user: user)
                return user
            } suc: {
                userManager.user = $0
            } fail: {
                showToast($0.message)
            }
        }
    }
    
    func deleteAccount() {
        if let user = userManager.user {
            request {
                //删除用户信息
                try await LeancloudManager.instance.del(todo: user)
                //注销用户登记,由于以及删除用户信息了，需要登记成功，所以使用了失败重试
                let logOffUserBean = LogOffUserBean()
                logOffUserBean.name = user.name
                if user.wx?.isEmpty == false {
                    logOffUserBean.id = user.wx
                } else if user.qq?.isEmpty == false {
                    logOffUserBean.id = user.qq
                } else if user.apple?.isEmpty == false {
                    logOffUserBean.id = user.apple
                } else if user.tourist?.isEmpty == false {
                    logOffUserBean.id = user.tourist
                }
                logOffUserBean.oldUserId = user.objectId
                logOffUserBean.loginType = user.loginType
                try await retry(maxRetries: 10, retryDelayMillis: 100) {
                    try await LeancloudManager.instance.save(todo: logOffUserBean)
                }
                return true
            } suc: { _ in
                userManager.doLogOut()
                pathManager.back()
            } fail: {
                showToast($0.message)
            }
        }
    }
}
